#pragma once
#include <iostream>
#include <string>
#include <unordered_map>

#include <functional>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;
// using http_handler_t = std::function<void(HttpRequest& , HttpRsonpse&)>;

class HttpServer
{
public:
    HttpServer(int port)
        :_tsvr(std::make_unique<TcpServer>(port))
    {

    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client){
                return this->HandlerHttpRequest(sockfd, client);
        });

        _tsvr->Loop(); 
    }

    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client : " << sockfd->Fd() << "addr info" << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);

        HttpRequest req;
        req.Deserialize(http_request);
        // req.Print();
        // std::cout<< "用户想要: " <<req.Uri() << std::endl;
        HttpResponse resp;
        resp.Build(req);
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;
    
        // HttpRequest hres;
        // hres.Deserialize(http_request);
        // hres.Print();
        // std::cout<< http_request;//字节流的请求
        // // 1,读取请求，对请求进行处理-->文本处理
        // // 2，完整的http反序列化， http response序列化...
        // // demo1：直接返回一个固定的内容
        // std::string status_line = "HTTp/1.1 200 OK" + Sep + BlankLine;

        // // 直接返回一个html网页
        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                    <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                    <p> Hello World</ p>\
        //                    </body> </html>";
            
        // std::string httpresponse = status_line + body;

        // sockfd->Send(httpresponse);      
        return true;
    }
    ~HttpServer()
    {

    }
private:
    std::unique_ptr<TcpServer> _tsvr;
    // std::unordered_map<std::string, http_handler_t> _route;// 功能路由
};

